import os
import logging

from functools import update_wrapper

import AppEnv
import base.Error
import models.Comment
import models.Post


__widget_list__ = {}

def register(wfunc, wname=None):
    if not wname:
        wname = wfunc.__name__
    __widget_list__[wname] = wfunc

def getWidget(wid):
    if not __widget_list__.has_key(wid):
        raise base.Error.PageNotFoundError('no this widget [%s]' % str(wid))
    return __widget_list__[wid]

def widgetMethod(f):
    def _wrap(*args, **argkw):
        handler = args[0]
        handler.templatedic['widgetName'] = f.__name__
        return f(*args,**argkw)
    func = update_wrapper(_wrap, f)
    register(func)
    return func

def loadWidgets():
    server_path = os.path.normpath(os.path.join(AppEnv.app_root, 'widgets'))
    mnames = set([k[:k.rfind('.')] for k in os.walk(server_path).next()[2] if (k.endswith('.py') or k.endswith('.pyc')) and not k.startswith('.') and not k.startswith('_')])
    for mname in mnames:
        try:
            __import__(mname, globals(), locals())
        except:
            logging.warn('import widget module [%s] failed.' % mname)
                       
loadWidgets()

@widgetMethod
def RecentComments(handler, params):
    """widgets method should have first arg be the BlogWidget instance
    """
    handler.templatedic['widgetName'] = 'Comments'
    size = 10
    if params:
        size = int(params[0])

    fetcher = models.Comment.Comment.all()
    if hasattr(handler, 'blog'):
        fetcher = fetcher.filter(' blog = ', handler.blog)
    comments = fetcher.order('-date').fetch(limit=size)
        
    handler.templatedic['comments'] = comments
    return
#register(RecentComments)

@widgetMethod
def BlogInfo(handler, params):
    """widget to show blog info
    """
    handler.templatedic['widgetName'] = handler.blog.blogName
    pass
#register(BlogInfo)

@widgetMethod
def Navigator(handler, params):
    linklist = []
    if handler.apppath:
        linklist.append({'text':'Home', 'href':'/'})
    linklist.append({'text':handler.appname, 'href':'%s' % (handler.apppath)})

    if handler.is_admin:
        linklist.append({'text':'Admin', 'href':'%s/admin' % handler.apppath})
    if handler.is_blogger:
        linklist.append({'text':'Your Blog', 'href':'%s/%s' % (handler.apppath, handler.is_blogger.blogId)})
        
    handler.templatedic['linklist'] = linklist
    return
#register(Navigator)

@widgetMethod
def Tags(handler, params):
    #all tags
    taglist = models.Tag.getTaglist(owner=getattr(handler, 'blog', None))
    handler.templatedic['taglist'] = taglist
    pass

@widgetMethod
def RecentPosts(handler, params):
    #all archives
    size = 10
    if params:
        size = int(params[0])
        
    fetcher = models.Post.Post.all()
    if hasattr(handler, 'blog'):
        fetcher = fetcher.filter(' blog = ', handler.blog)
    postlist = fetcher.order('-date').fetch(limit=size)
    handler.templatedic['postlist'] = postlist
    return

@widgetMethod
def Archives(handler, params):
    #all archives
    arlist = models.Post.getArlist(blog=getattr(handler, 'blog', None))
    handler.templatedic['arlist'] = arlist
    return

